Luna = {}
Luna.Addons = {}
Luna.MsgQueue = {}
Luna.MsgReceive = {}
Luna.Player = nil
Luna.MsgSize = 400
Luna.SetTimer = 2
Luna.Timer = Luna.SetTimer
Luna.ErrorTimer = 0
Luna.ConnectTimer = 30
Luna.ConnectAction = "JOIN";
Luna.ChannelNumber = 0
Luna.Locale = {}
Luna.Author = "Mavoc"
Luna.Version = "v1.0.1"
Luna.Build = tonumber("25")
Luna.CurrentVersion = Luna.Version
Luna.CurrentBuild = Luna.Build
dofile("Interface/Addons/Luna/Locales/"..string.sub(GetLocation(),1,2)..".lua")

function Luna.RegisterAddon(addonname, functionname)
	Luna.Addons[addonname] = functionname
	Luna.MsgReceive[addonname] = {}
	--[===[@alpha@
	local msg = string.gsub(Luna.Locale.AddonRegistered, "<AddonName>", addonname)
	DEFAULT_CHAT_FRAME:AddMessage(msg)
	--@end-alpha@]===]
end

function Luna.UnregisterAddon(addonname)
	Luna.Addons[addonname] = nil
	Luna.MsgReceive[addonname] = nil
	--[===[@alpha@
	local msg = string.gsub(Luna.Locale.AddonUnregistered, "<AddonName>", addonname)
	DEFAULT_CHAT_FRAME:AddMessage(msg)
	--@end-alpha@]===]
end

function Luna.QueueMessage(addonname, msg)
	table.insert(Luna.MsgQueue, {["addonname"] = addonname, ["msg"] = msg, ["page"] = 1, ["total"] = math.ceil(string.len(msg) / Luna.MsgSize)})
	--[===[@alpha@
	local msg = string.gsub(Luna.Locale.DebugQueueMessage, "<AddonName>", addonname)..#(Luna.MsgQueue)
	DEFAULT_CHAT_FRAME:AddMessage(msg)
	--@end-alpha@]===]
end

function Luna.SendMessage()
	if #(Luna.MsgQueue) > 0 and Luna.ChannelNumber > 0 then
		SendChatMessage("|H"..Luna.MsgQueue[1]["page"].."/"..Luna.MsgQueue[1]["total"].."/"..string.sub(Luna.MsgQueue[1]["msg"], ((Luna.MsgQueue[1]["page"]-1)*Luna.MsgSize)+1, Luna.MsgQueue[1]["page"]*Luna.MsgSize).."|h"..Luna.MsgQueue[1]["addonname"].."|h", "CHANNEL", 0, Luna.ChannelNumber)
		if Luna.MsgQueue[1]["page"] == Luna.MsgQueue[1]["total"] then
			table.remove(Luna.MsgQueue, 1)
		else
			Luna.MsgQueue[1]["page"] = Luna.MsgQueue[1]["page"] + 1
		end
	end
	Luna.Timer = Luna.SetTimer
end

function Luna.Luna(SenderName, SenderMessage)
	if string.match(SenderMessage, "Build: %d+ Version: v[%d.]+") then
		if Luna.CurrentBuild < tonumber(string.match(SenderMessage, "%d+")) then
			Luna.CurrentBuild = tonumber(string.match(SenderMessage, "%d+"))
			Luna.CurrentVersion = string.match(SenderMessage, "v[%d.]+", 16)
			local msg = string.gsub(Luna.Locale.NewerVersion, "<VersionNumber>", Luna.CurrentVersion.."."..Luna.CurrentBuild)
			DEFAULT_CHAT_FRAME:AddMessage(msg)
		end
	end
end

function Luna_OnLoad(this)
    this:RegisterEvent("VARIABLES_LOADED");
    this:RegisterEvent("CHAT_MSG_CHANNEL");
    this:RegisterEvent("CHAT_MSG_SYSTEM");  
end

function Luna_OnEvent(event)
	if event == "CHAT_MSG_CHANNEL" then
		if GetChannelName(arg3) == "Luna" then
			if DEFAULT_CHAT_FRAME.channelList[arg3] ~= nil then
				DEFAULT_CHAT_FRAME.channelList[arg3] = nil
			end
			if string.match(arg1, Luna.Locale.OneventJoinedChannel) then
				if UnitName("player") == nil or string.match(arg1, UnitName("player")) then
					Luna.ChannelNumber = arg3
					Luna.ConnectTimer = -1
					DEFAULT_CHAT_FRAME:AddMessage(Luna.Locale.JoinChannelMessage)
					--@non-alpha@
					Luna.QueueMessage("Luna", "Build: "..Luna.Build.." Version: "..Luna.Version)
					--@end-non-alpha@
				end
			elseif string.match(arg1, Luna.Locale.OneventLeftChannel) then
				if UnitName("player") ~= nil and string.match(arg1, UnitName("player")) then
					Luna.ConnectTimer = 3
					Luna.ChannelNumber = 0
					DEFAULT_CHAT_FRAME:AddMessage(Luna.Locale.LeaveChannelMessage)
				end
			elseif string.match(arg1, "|H%d+/%d+/[%a%d%s-!#$%&'()*+,./%\:;<=>?@[%]{}_`~]+|h[%a%d%s-!#$%&'()*+,./%\:;<=>?@[%]{}_`~]+|h") and arg4 ~= Luna.Player then
				if Luna.Addons[string.sub(string.match(arg1, "|h[%a%d%s%-%(%)%{%}%[%],.]+"), 3)] then
					local Temp = arg1
					local Page = ""
					local Total = ""
					local Message = ""
					local PlayerName = arg4
					if string.match(PlayerName, "%[(.+)%-(.+)%]") then
						PlayerName = string.gsub(PlayerName, "%[(.+)%-", "%[");
					end
					local AddonName = ""
					Page = tonumber(string.match(Temp, "%d+"))
					Temp = string.gsub(Temp, "|H%d+/", "", 1)
					Total = tonumber(string.match(Temp, "%d+"))
					Temp = string.gsub(Temp, "%d+/", "", 1)
					Message = string.match(Temp, "[%a%d%s-!#$%&'()*+,./%\:;<=>?@[%]{}_`~]+")
					AddonName = string.sub(string.match(arg1, "|h[%a%d%s-!#$%&'()*+,./%\:;<=>?@[%]{}_`~]+"), 3)
					if Page == 1 then
						Luna.MsgReceive[AddonName][PlayerName] = Message
					elseif Page > 1 then
						Luna.MsgReceive[AddonName][PlayerName] = Luna.MsgReceive[AddonName][PlayerName]..Message
					end
					if Page == Total and Page ~= "" then
						Luna.Addons[AddonName](PlayerName, Luna.MsgReceive[AddonName][PlayerName])
						Luna.MsgReceive[AddonName][PlayerName] = nil
					end
				end
			end
		end
    elseif event == "CHAT_MSG_SYSTEM" then
		if arg1 == Luna.Locale.OneventJoinFailed then
			Luna.ConnectTimer = 3;
			Luna.ConnectAction = "CREATE";
		elseif arg1 == Luna.Locale.OneventCreateFailed then
			Luna.ConnectTimer = 3;
			Luna.ConnectAction = "JOIN";        
		end
	elseif event == "VARIABLES_LOADED" then
		if AddonManager then
			local addon = {
				name = "Luna",
				version = Luna.Version.."."..Luna.Build,
				author = Luna.Author,
				description = Luna.Locale.Description,
				icon = nil,
				category = "Development",
				configFrame = nil, 
				slashCommand = nil,
				miniButton = nil,
				disableScript = nil,
				enableScript = nil,
			}
			if AddonManager.RegisterAddonTable then
				AddonManager.RegisterAddonTable(addon)
			else
				AddonManager.RegisterAddon(addon.name, addon.description, addon.icon, addon.category, addon.configFrame, addon.slashCommand, addon.miniButton, addon.version, addon.author)
			end
		end
		Luna.RegisterAddon("Luna", Luna.Luna)
		Luna.ConnectTimer = 1
	end
end

function Luna_OnUpdate(update, elapsedTime)
	Luna.Timer = Luna.Timer - elapsedTime
	if Luna.Timer <= 0 then
		Luna.SendMessage()
	end
	if not Luna.Player and UnitName("player") then Luna.Player = UnitName("player") end
	if Luna.ConnectTimer <= 1 and Luna.ConnectTimer >= 0 then
		Luna.ConnectTimer = -1
		Luna.ErrorTimer = GetTime()
		if Luna.ConnectAction == "JOIN" then
			JoinChannel("Luna", "Luna")
		else
			CreateChannel("Luna", "Luna")
		end
	elseif Luna.ConnectTimer > 1 then
		Luna.ConnectTimer = Luna.ConnectTimer - elapsedTime
	elseif Luna.ErrorTimer > 0 then
		Luna.ErrorTimer = Luna.ErrorTimer - elapsedTime
	elseif Luna.ConnectTimer == -1 and Luna.ChannelNumber == 0 and Luna.ErrorTimer + 3 >= GetTime()then
		local channellist = {GetChannelList()}
		for i,v in ipairs(channellist) do
			if v == "Luna" then
				Luna.ChannelNumber = i/2
				DEFAULT_CHAT_FRAME:AddMessage(Luna.Locale.JoinChannelMessage)
				--@non-alpha@
				Luna.QueueMessage("Luna", "Build: "..Luna.Build.." Version: "..Luna.Version)
				--@end-non-alpha@
				break
			end
		end
		if Luna.ChannelNumber == 0 then
			Luna.ConnectTimer = 3
		end
	end
end